/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosn.framework.database;

import javax.persistence.EntityManager;

/**
 *
 * @author selkhateeb
 */
public abstract class Controller
{

    public final void Save() throws Exception
    {
        EntityManager em = null;
        try
        {
            em = DatabaseEntityManager.getEntityManager();
            em.getTransaction().begin();
            em.persist(this);
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public final void Delete() throws Exception
    {
        EntityManager em = null;
        try
        {
            em = DatabaseEntityManager.getEntityManager();
            em.getTransaction().begin();
            em.remove(em.merge(this));
            em.getTransaction().commit();
        } catch (Exception e)
        {
            throw e;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public final void Update() throws Exception
    {
        EntityManager em = null;
        try
        {
            em = DatabaseEntityManager.getEntityManager();
            em.getTransaction().begin();
            em.merge(this);
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }

    }

    public int getPollCount()
    {
        EntityManager em = DatabaseEntityManager.getEntityManager();
        try
        {
            return ((Long) em.createQuery("select count(o) from Poll as o").getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }
}
